package com.color.admin.system.servie.impl;


import com.color.admin.common.core.constant.Constant;
import com.color.admin.common.core.exception.BaseException;
import com.color.admin.common.core.page.PageRequest;
import com.color.admin.common.core.page.PageResponse;
import com.color.admin.common.core.utils.tools.QueryHelp;
import com.color.admin.system.entity.SysPost;
import com.color.admin.system.entity.SysUser;
import com.color.admin.system.entity.query.PostQueryCriteria;
import com.color.admin.system.entity.vo.post.PostSmallVo;
import com.color.admin.system.entity.vo.post.PostVo;
import com.color.admin.system.repository.PostRepository;
import com.color.admin.system.servie.PostService;
import com.color.admin.system.servie.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author HaiQiu
 * @date 2021/12/28
 */
@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private UserService userService;

    @Override
    public void save(SysPost sysPost) {
        sysPost.setCreateTime(new Date());
        sysPost.setUpdateTime(new Date());
        SysPost post = postRepository.save(sysPost);
        if (ObjectUtils.isEmpty(post)){
            throw new BaseException(Constant.INSERT_FAIL);
        }
    }

    @Override
    public void update(SysPost sysPost) {
        if (!StringUtils.hasText(sysPost.getId())) {
            throw new BaseException(Constant.ID_EXITS);
        }
        SysPost post = postRepository.findById(sysPost.getId()).orElseGet(SysPost::new);
        if (ObjectUtils.isEmpty(post)){
            throw new BaseException("数据不存在");
        }
        post.setUpdateTime(new Date());
        post.setActive(sysPost.getActive());
        post.setDescription(sysPost.getDescription());
        post.setPostName(sysPost.getPostName());
        post.setIcon(sysPost.getIcon());
        post.setSort(sysPost.getSort());
        postRepository.save(post);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Set<String> postIds) {
        if (CollectionUtils.isEmpty(postIds)){
            throw new BaseException(Constant.ID_EXITS);
        }
        List<SysUser> sysUsers = userService.findUserByPostIds(postIds);
        List<String> collect = sysUsers.stream().map(SysUser::getUsername).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(sysUsers)){
            throw new BaseException(String.format(Constant.OCCUPY,collect,"岗位"));
        }
        if (postRepository.deleteAllByIdIn(postIds)==0){
            throw new BaseException(Constant.DELETE_FAIL);
        }
    }

    @Override
    public SysPost get(String postId) {
        SysPost sysPost = postRepository.findById(postId).orElseGet(SysPost::new);
        if (ObjectUtils.isEmpty(sysPost) && !sysPost.getId().equals(postId)){
            throw new BaseException(Constant.DATA_EXITS);
        }
        return sysPost;
    }

    @Override
    public List<PostSmallVo> postAll(String postName) {
        List<SysPost> sysPosts = postRepository.findAll();
        return getPostSmallVo(sysPosts);
    }

    @Override
    public PageResponse<PostVo> list(PageRequest<PostQueryCriteria> request) {
        //获取注解查询参数
        PostQueryCriteria criteria = request.getParams();
        //排序
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.ASC,"sort"));
        orders.add(new Sort.Order(Sort.Direction.DESC,"updateTime"));
        //分页
        Pageable pageable = org.springframework.data.domain.PageRequest.of(request.getNum(),
                request.getPageSize(), Sort.by(orders));
        //查询
        Page<SysPost> sysPosts = postRepository.findAll(((root, query, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder)), pageable);
        //转换
        Page<PostVo> postVos = sysPosts.map(sysPost -> {
            PostVo vo = new PostVo();
            BeanUtils.copyProperties(sysPost,vo);
            return vo;
        });
        //赋值返回
        PageResponse<PostVo> response = new PageResponse<>();
        response.setData(postVos.getContent());
        response.setPageSize(request.getPageSize());
        response.setPageIndex(request.getPageIndex());
        response.setTotalElements(postVos.getTotalElements());
        return response;
    }

    protected List<PostSmallVo> getPostSmallVo(List<SysPost> sysPosts){
        List<PostSmallVo> postSmallVoList = sysPosts.stream().map(sysPost -> {
            PostSmallVo vo = new PostSmallVo();
            BeanUtils.copyProperties(sysPost, vo);
            return vo;
        }).collect(Collectors.toList());
        return postSmallVoList;
    }
}
